/* eslint-disable @typescript-eslint/no-explicit-any */
// import { isArray } from 'lodash';
import * as R from "ramda";


function isArray(val: any): val is Array<any> {
  return val && Array.isArray(val);
}


export default () => {
  const flattenFn = (list: any[], e: string): number[] => {
    const arr: number[][] = [];
    list.forEach((v, i) => {
      if (i === 0) {
        arr.push([1]);
      } else if (R.equals(v[e], list[i - 1][e])) {
        arr[arr.length - 1][0]+=1;
        arr[arr.length - 1].push(0);
      } else {
        arr.push([1]);
      }
    });
    return R.flatten(arr);
  };

  const changeRow = (list: number[]): number[] => {
    const array: number[][] = [];
    list.forEach((e: number, i: number) => {
      if (i === 0) {
        array.push([1]);
      } else if (R.equals(e, list[i - 1])) {
        array[array.length - 1][0]+=1;
        array[array.length - 1].push(0);
      } else {
        array.push([1]);
      }
    });

    return R.flatten(array);
  };

  // const flattenRowFn = (list: any[], colList: string[]): number[][] => {
  //   const arr: number[][] = [];
  //   list.forEach((v) => {
  //     arr.push(changeRow(colList.map((key) => v[key])));
  //   });
  //   return arr;
  // };

  const flattenRowFn2 = (list: any[], colList: string[][]): number[][][] => {
    const arr: number[][][] = [];
    list.forEach((v) => {
      arr.push(colList.map((col: any[]) => changeRow(col.map((key) => v[key]))));
    });
    return arr;
  };
  
  const listAppendFn = (
    list: any[],
    merge: string[] | boolean,
    colList: string[][]
  ) => {
    if (typeof merge === 'boolean') {
      if (!merge) return list;
    } else {
      const objCol: any = {};
      merge.forEach((e) => {
        objCol[e] = flattenFn(list, e);
      });

      for (const key in objCol) {
        list.forEach((v, i) => {
          v.customCell || (v.customCell = {});
          v.customCell[key] = { rowSpan: objCol[key][i] };
        });
      }
      
      const flat = flattenRowFn2(list, colList);

      list.forEach((v, i) => {
          colList.forEach((s, index) => {
            if(isArray(s)){
              s.forEach((t, num) => {
                v.customCellCol || (v.customCellCol = {});
                v.customCellCol[t] = { colSpan: flat[i][index][num] };
              });
            }
          });

        });
      return list;
    }
  };

  return { listAppendFn };
};
